package com.zxcl.service.impl;


import com.zxcl.constant.AuthConstant;
import com.zxcl.strategy.LoginStrategy;
import com.zxcl.strategy.factory.LoginStrategyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述: [和security结合的登录处理]
 * 作者: zxcl
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    /**
     * 拓展框架 的核心逻辑
     * B2C
     * 至少有两种用户体系
     * 管理员登录 sys_user
     * 会员登录   member
     * zhangsan 123456
     * 和前台约定好 在header中携带一个loginType
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取用户登录类型
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        if (!StringUtils.hasText(loginType)) {
            throw new InternalAuthenticationServiceException("非法登录，登录类型为空");
        }
        // 策略模式     多种情况 每种情况都对应不同的处理方案
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        if (ObjectUtils.isEmpty(instance)) {
            throw new InternalAuthenticationServiceException("非法登录，登录类型不匹配");
        }
        return instance.realLogin(username);
    }

}
